package com.xunlai.infra.permission.business.controller;

import cn.hutool.core.lang.UUID;
import com.xunlai.infra.permission.business.service.PhotoGalleryService;
import com.xunlai.infra.permission.business.vo.photoGallery.PhotoBatchCreateVo;
import com.xunlai.infra.permission.business.vo.photoGallery.PhotoCreateVo;
import com.xunlai.infra.permission.business.vo.photoGallery.PhotoListVo;
import com.xunlai.infra.permission.business.vo.photoGallery.QrCodeGenerateVo;
import com.xunlai.infra.permission.common.constant.ExtendClaimsConstants;
import com.xunlai.infra.permission.common.exception.ExceptionCodeEnum;
import com.xunlai.infra.permission.common.security.TenantUser;
import com.xunlai.infra.permission.common.vo.BasePageRespVo;
import com.xunlai.infra.permission.common.vo.BaseResponse;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.core.OAuth2AuthenticatedPrincipal;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;

/**
 * @author liang
 * @date 8/7/23 7:13 PM
 */
@RestController
@RequestMapping("travel/manage/photo")
public class PhotoManageController {

    private final Logger logger = LoggerFactory.getLogger(PhotoManageController.class);

    private PhotoGalleryService photoGalleryService;


    @PostMapping("upload")
    public BaseResponse<String> uploadPhoto(@RequestParam("file") MultipartFile file){
        return BaseResponse.success(photoGalleryService.uploadPhoto(file));
    }

    @PostMapping("upload/batch")
    public BaseResponse<List<String>> batchUploadPhoto(@RequestParam("file") MultipartFile[] file){
        return BaseResponse.success(photoGalleryService.batchUploadPhoto(file));
    }

    @PostMapping("create")
    public BaseResponse<Long> createPhoto(@RequestBody PhotoCreateVo photoCreateVo){
        return BaseResponse.success(photoGalleryService.createPhoto(photoCreateVo));
    }

    @PostMapping("create/batch")
    public BaseResponse<List<Long>> batchCreatePhoto(@RequestBody PhotoBatchCreateVo photoBatchCreateVo){
        return BaseResponse.success(photoGalleryService.batchCreatePhoto(photoBatchCreateVo));
    }

    @PutMapping("update/{id}")
    public BaseResponse<Void> updatePhoto(@PathVariable Long id,@RequestBody PhotoCreateVo photoCreateVo){
        photoGalleryService.updatePhoto(id, photoCreateVo);
        return BaseResponse.success();
    }

    @GetMapping("list")
    public BaseResponse<BasePageRespVo<PhotoListVo>> listPhotos(@RequestParam(required = false) String photoType,
                                                  @RequestParam(required = false)String name,
                                                  @RequestParam(required = false)String scenicName,
                                                  @RequestParam(required = false,defaultValue = "1")Integer pageNum,
                                                  @RequestParam(required = false,defaultValue = "10")Integer pageSize,
                                                  @AuthenticationPrincipal OAuth2AuthenticatedPrincipal pri){
//        String id = pri.getAttribute(ExtendClaimsConstants.ID);
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        Object principal = authentication.getPrincipal();
        if(principal instanceof TenantUser tenantUser){
            String id = tenantUser.getId();
            return BaseResponse.success(photoGalleryService.listPhoto(null,scenicName,photoType,name,id,pageNum,pageSize,false));
        }else {
            return BaseResponse.error(ExceptionCodeEnum.NOT_LOGIN);
        }
    }

    @GetMapping("official/list")
    public BaseResponse<BasePageRespVo<PhotoListVo>> listOfficialPhotos(
                                                    @RequestParam(required = false) String scenicProvince,
                                                    @RequestParam(required = false)String scenicName,
                                                    @RequestParam(required = false) String photoType,
                                                  @RequestParam(required = false)String name,
                                                  @RequestParam(required = false,defaultValue = "1")Integer pageNum,
                                                  @RequestParam(required = false,defaultValue = "10")Integer pageSize){
        return BaseResponse.success(photoGalleryService.listPhoto(scenicProvince,scenicName,photoType,name,null,pageNum,pageSize,true));
    }

    @DeleteMapping("delete/{id}")
    public BaseResponse<Void> delete(@PathVariable Long id){
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        Object principal = authentication.getPrincipal();
        if(principal instanceof TenantUser tenantUser){
            String userId = tenantUser.getId();
            photoGalleryService.deletePhoto(Long.valueOf(userId),id);
        }else {
            return BaseResponse.error(ExceptionCodeEnum.NOT_LOGIN);
        }
        return BaseResponse.success();
    }

    @PreAuthorize("hasRole('ADMIN')")
    @DeleteMapping("official/delete/{id}")
    public BaseResponse<Void> deleteOfficial(@PathVariable Long id){
        photoGalleryService.deletePhoto(id);
        return BaseResponse.success();
    }

    @GetMapping("qrCode/generate")
    public void generateQrCode(QrCodeGenerateVo qrCodeGenerateVo , HttpServletResponse response){
        try {
            photoGalleryService.createQrCodeToStream(qrCodeGenerateVo,response.getOutputStream());
        } catch (IOException e) {
            logger.error(e.getMessage(),e);
        }
    }



    @Autowired
    public void setPhotoGalleryService(PhotoGalleryService photoGalleryService) {
        this.photoGalleryService = photoGalleryService;
    }
}
